package com.onyx.service.impl;

import com.onyx.constant.Constant;
import com.onyx.entity.OrderTarget;
import com.onyx.entity.VoOrderTarget;
import com.onyx.interceptor.UserContext;
import com.onyx.mapper.OrderTargetMapper;
import com.onyx.service.OrderTargetService;
import com.onyx.utils.NumUtil;
import com.onyx.utils.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
public class OrderTargetServiceImpl implements OrderTargetService {

    @Autowired
    private OrderTargetMapper orderTargetMapper;

    private static Logger logger = LoggerFactory.getLogger(OrderTargetServiceImpl.class);
    @Override
    public Pair<String, String> queryTargets() {
        String now = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now());
        String order0 = orderTargetMapper.getNowOrder(0L, now);
        String order1 = orderTargetMapper.getNowOrder(UserContext.getUser().getId(), now);
        if (StringUtils.isBlank(order0)) {
            order0 = Constant.DEFAULT_MONEY;
        }
        if (StringUtils.isBlank(order1)) {
            order1 = Constant.DEFAULT_MONEY;
        }
        return Pair.of(order0, order1);
    }

    @Override
    public void addTarget(OrderTarget orderTarget) {
        orderTarget.setUserId(UserContext.getUser().getId());
        orderTarget.setTargetState(0);
        orderTargetMapper.addTarget(orderTarget);
    }

    @Override
    public Page<VoOrderTarget> getTargets(Map<String, Object> data) {
        List<VoOrderTarget> list = orderTargetMapper.queryTargets(data);
        int targetsNum = orderTargetMapper.queryTargetsNum(data);
        Page<VoOrderTarget> page = new Page<>(NumUtil.num2Int(data.get("pageNo")), targetsNum, list);
        return page;
    }

    @Override
    public void doneTarget(Map<String, Object> map) {
        orderTargetMapper.doneTarget(map);
    }

    @Override
    public void modifyTarget(OrderTarget orderTarget) {
        orderTarget.setUserId(UserContext.getUser().getId());
        orderTargetMapper.modifyTarget(orderTarget);
    }

    @Override
    public void deleteTarget(Long id) {
        orderTargetMapper.deleteTarget(id);
    }

    @Override
    public OrderTarget getOneTarget(Long id) {
        return orderTargetMapper.getOneTarget(id);
    }
}
